class Contract < ActiveRecord::Base
  has_many :contract_items, dependent: :destroy
  
  accepts_nested_attributes_for :contract_items
  
  #====== validations =========
  validates_presence_of :contract_code, :buyer, :seller
  validates_associated :contract_items  
  
  
  
  # Constructor with default contract_code and contract_date
  # def initialize()
    # set_contract_code
    # set_contract_date 
  # end


  # Generate Default Contract_Code
  # Contract_Code format: JBTX-YYYYMMDD-contract_count
  def set_contract_code 
    self.contract_code = "JBTX-"+Time.now.strftime("%Y%m%d-")+get_table_count(Time.now.strftime("%Y-%m-%d")).to_s
  end
  
  # Generate Default Contract_date
  def set_contract_date
    self.contract_date = Time.now.strftime("%Y-%m-%d")
  end
  
  def get_table_count(contract_date) 
    Contract.where(["contract_date=?",contract_date]).count+1
  end
  
  def set_buyer_info(buyer)
    self.buyer = buyer.name
    self.buyer_address = buyer.address
    self.buyer_bank = buyer.bank
    self.buyer_bank_account = buyer.bank_account
  end
  
  def set_seller_info(seller)
    self.seller = seller.name
    self.seller_address = seller.address
    self.seller_bank = seller.bank
    self.seller_bank_account = seller.bank_account
  end
  
  # Calculate the total amount of this contract by summing up amounts of all items
  def cal_total
    self.total = 0
    self.contract_items.each do |i|
      self.total += i.amount
    end     
  end
  
  # get Seller info
  def get_seller_info
      seller = Company.new
      seller.name = self.seller
      seller.address = self.seller_address
      seller.tel = self.seller_tel
      seller.fax = self.seller_fax
      seller.bank = self.seller_bank
      seller.bank_account = self.seller_bank_account
      
      return seller
  end
  
  # get Buyer info
  def get_buyer_info
      buyer = Company.new
      buyer.name = self.buyer
      buyer.address = self.buyer_address
      buyer.tel = self.buyer_tel
      buyer.fax = self.buyer_fax
      buyer.bank = self.buyer_bank
      buyer.bank_account = self.buyer_bank_account
      
      return buyer
  end
end
